from flask import Flask, render_template, request, redirect, url_for, flash
import csv
import os
from difflib import SequenceMatcher
from datetime import datetime

app = Flask(__name__)
app.secret_key = 'your-secret-key-here'  # 请更换为实际的安全密钥
DATA_FILE = 'data.csv'
MAX_TOPICS_PER_STUDENT = 3

# 初始化CSV文件
def init_csv():
    if not os.path.exists(DATA_FILE):
        with open(DATA_FILE, 'w', newline='', encoding='gbk') as f:
            writer = csv.writer(f)
            writer.writerow(['姓名', '学号', '话题', '提交时间'])

# 获取学号的话题数量
def get_student_topic_count(student_id):
    count = 0
    try:
        with open(DATA_FILE, 'r', encoding='gbk') as f:
            reader = csv.DictReader(f)
            for row in reader:
                if row['学号'] == student_id:
                    count += 1
    except FileNotFoundError:
        pass
    return count

@app.route('/', methods=['GET', 'POST'])
def index():
    init_csv()
    
    # 读取历史数据
    history = []
    try:
        with open(DATA_FILE, 'r', encoding='gbk') as f:
            reader = csv.DictReader(f)
            history = list(reader)
    except FileNotFoundError:
        history = []
    
    if request.method == 'POST':
        name = request.form['name'].strip()
        student_id = request.form['student_id'].strip()
        topics_input = request.form['topic'].strip()
        
        # 验证学号格式
        if not (student_id.startswith('f') and len(student_id) == 9 and student_id[1:].isdigit()):
            flash('学号格式应为f开头+8位数字')
            return render_template('index.html', history=history)
        
        # 处理多行话题输入，只取前3行
        topics = [line.strip() for line in topics_input.split('\n') if line.strip()]
        if len(topics) > 3:
            topics = topics[:3]
            flash('检测到多个话题，已自动取前3个')
        elif len(topics) == 0:
            flash('请至少输入一个话题')
            return render_template('index.html', history=history)
        
        # 检查学号的话题数量
        current_count = get_student_topic_count(student_id)
        if current_count >= MAX_TOPICS_PER_STUDENT:
            flash(f'该学号已达到最大报名数({MAX_TOPICS_PER_STUDENT}个)，请联系管理员修改')
            return render_template('index.html', history=history)
        
        # 提交每个话题
        for topic in topics:
            # 检查学号是否已存在（针对当前学号无任何话题的情况）
            if current_count == 0:
                existing_entry = None
                try:
                    with open(DATA_FILE, 'r', encoding='gbk') as f:
                        reader = csv.DictReader(f)
                        for row in reader:
                            if row['学号'] == student_id:
                                existing_entry = row
                                break
                except FileNotFoundError:
                    pass
                
                if existing_entry:
                    flash(f'学号{student_id}已提交话题："{existing_entry["话题"]}"，是否修改？')
                    return render_template('index.html', history=history, name=name, 
                                        student_id=student_id, topic='\n'.join(topics))
            
            # 检查话题相似度（阈值0.8）
            is_duplicate_topic = False
            try:
                with open(DATA_FILE, 'r', encoding='gbk') as f:
                    reader = csv.DictReader(f)
                    for row in reader:
                        similarity = SequenceMatcher(None, topic.lower(), row['话题'].lower()).ratio()
                        if similarity > 0.8:
                            is_duplicate_topic = True
                            break
            except FileNotFoundError:
                pass
            
            if is_duplicate_topic:
                flash(f'话题"{topic}"与已有内容高度相似，请修改后重新提交！')
                return render_template('index.html', history=history, name=name, 
                                    student_id=student_id, topic='\n'.join(topics))
            
            # 写入新数据
            timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            with open(DATA_FILE, 'a', newline='', encoding='gbk') as f:
                writer = csv.writer(f)
                writer.writerow([name, student_id, topic, timestamp])
        
        flash('报名成功！')
        return redirect(url_for('index'))
    
    return render_template('index.html', history=history)

if __name__ == '__main__':
    # 确保目录存在
    if not os.path.exists('templates'):
        os.makedirs('templates')
    if not os.path.exists('static'):
        os.makedirs('static')
    
    # 启动开发服务器
    app.run(debug=True, host='0.0.0.0', port=5000)